/**
 * @file ext-link.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */

const name = 'datatext'

const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
  name,
  async init()
  {
    const svgEditor = this
    const { svgCanvas } = svgEditor
    const { ChangeElementCommand } = svgCanvas.history
    const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
    const { $id, $click, $qq } = svgCanvas
    let started
    let newFO
    let p = {
      x: 0, y: 0, x1: 0, y1: 0, cssstyle: { "font-size": 12, "font-family": svgCanvas.getCurText('font_family') }
    }
    await loadExtensionTranslation(svgEditor)

    /**
     *
     * @param {string} attr attribute to change
     * @param {string|Float} val new value
     * @returns {void}
     */
    const isGecko = navigator.userAgent.includes('Gecko/')
    const setAttrs = (elem, attrs) => {
      if (isGecko) {
        Object.entries(attrs).forEach(([aname, val]) => {
          elem.setAttribute(aname, val)
        })
      } else {
        Object.entries(attrs).forEach(([aname, val]) => {
          const prop = elem[aname]
          if (prop?.constructor === 'SVGLength') {
            prop.baseVal.value = val
          } else {
            elem.setAttribute(aname, val)
          }
        })
      }
    }

    const createG = (id, className) => {
      newFO = svgCanvas.addSVGElementsFromJson({
        element: 'g',
        attr: {
          class: className,
          id: id,
          'doc-type': 'datatext',
        }
      })
      // newFO.addEventListener('mouseover', function () {
      //   if (this.getAttribute("state")) {
      //     var d = JSON.parse(decodeURIComponent(escape(atob(newFO.getAttribute("state")))))
      //     svgCanvas.getCurrentDrawing().current_layer.setName(d.chooseName)
      //   }
      // })
      // newFO.addEventListener('mouseout', function () {
      //   svgCanvas.getCurrentDrawing().current_layer.setName("图层 1")
      // })
    }

    const createTextNode = (p, id) => {
      var text = svgCanvas.addSVGElementsFromJson({
        element: 'text',
        attr: {
          x: p.x,
          y: p.y,
          id: id + "_text",
          'stroke-width': 1,
          'stroke': 'red'
        }
      })
      text.textContent = "####.###"
      newFO.append(text)
      setAttrs(text, p.cssstyle)
    }

    return {
      name: svgEditor.i18next.t(`${name}:name`),
      // The callback should be used to load the DOM with the appropriate UI items
      callback() {
        // Add the button and its handler(s)
        // Note: the star extension needs to be loaded before the polygon extension
        const fbtitle = `${name}:title`
        const titleStar = `${name}:buttons.0.title`
        const titlePolygon = `${name}:buttons.1.title`
        const buttonTemplate = `
              <se-button id="tool_datatext" title="${titlePolygon}" src="datatext.svg">
              </se-button>
          `
        svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 2)

        $click($id('tool_datatext'), () => {
          if (this.leftPanel.updateLeftPanel('tool_datatext')) {
            svgCanvas.setMode('datatext')
          }
        })
      },
      mouseDown(opts) {
        if (svgCanvas.getMode() === 'datatext') {
          started = true
          p.x = opts.start_x
          p.y = opts.start_y
          var id = svgCanvas.getNextId()
          createG(id, "ems")
          createTextNode(p, id)
          return {
            started: true
          }
        }
        return undefined
      },
      mouseMove(opts) {
        if (!started) {
          return undefined
        }
        if (svgCanvas.getMode() === 'datatext') {
          return {
            started: true
          }
        }
        return undefined
      },
      mouseUp() {
        if (svgCanvas.getMode() === 'datatext') {
          const keep = true
          // svgCanvas.addToSelection([newFO], true);
          return {
            keep,
            element: newFO
          }
        }
        return undefined
      },
      sourceChanged(opts) {
        let elem = opts.elems[0];
        if (!elem) return;
        if (elem.tagName === 'svg' && elem.id === 'svgcontent') {
          // Update svgContent (can change on import)
          var svgContent = elem;
          // var foreignObjects = $(svgContent).find(".ems")
          // Array.from(foreignObjects).forEach((elem, i) => {
          //   var docType = $(elem).attr("doc-type")
          //   if (docType == "datatext" || docType == "KG" || docType == "DZ") {
          //     elem.addEventListener('mouseover', function () {
          //       try {
          //         if (this.getAttribute("state")) {
          //           var d = JSON.parse(decodeURIComponent(escape(atob(this.getAttribute("state")))))
          //           svgCanvas.getCurrentDrawing().current_layer.setName(d.chooseName)
          //         }
          //       } catch (e) {
          //         console.log(e)
          //       }
          //     })
          //     elem.addEventListener('mouseout', function () {
          //       svgCanvas.getCurrentDrawing().current_layer.setName("图层 1")
          //     })
          //   }
          // })
        }
      },
      updateDatatext(opts) {
        if (opts.mode != "datatext") {
          return
        }
        const elem = svgCanvas.getSelectedElements()[0]
        if (elem == null) return
        var data = opts.data
        var cssstyle = data?.cssstyle || p.cssstyle
        const oldValues = {
          fontFamily:elem.firstChild.getAttribute("font-family"),
          fontSize:elem.firstChild.getAttribute("font-size"),

        }

        addToHistory(new ChangeElementCommand(elem.firstChild,oldValues))
        elem.firstChild.removeAttribute("font-weight")
        elem.firstChild.removeAttribute("font-style")
        elem.firstChild.removeAttribute("text-decoration")
        // 图形的数据都在动态数据的firstChild中。
        setAttrs(elem.firstChild, cssstyle)
        if (data.fontdir) {
          elem.firstChild.setAttribute("writing-mode", data.fontdir)
        }
        var txt = ""
        var inter = data.Displaylength - data.Decimalplaces
        // 动态数据划分小数数据和最大位数
        for (var i = 0; i < inter; i++) {
          txt += "#"
        }
        if (data.Decimalplaces > 0) {
          txt += "."
        }
        for (var i = 0; i < data.Decimalplaces; i++) {
          txt += "#"
        }
        elem.firstChild.textContent = txt
        svgCanvas.recalculateDimensions(elem)
        svgCanvas.selectorManager.requestSelector(elem).resize()
        elem.firstChild.setAttribute("width", 120);
        elem.setAttribute("state", btoa(unescape(encodeURIComponent(JSON.stringify(data)))))
        elem.setAttribute("data", `${data.tableValue}:${data.equipmentLable}:${data.domainID}`)
        svgEditor.layersPanel.populateObjects()

      }
    }
  }
}
